package com.senac.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.senac.model.Usuario;
import com.senac.service.UsuarioService;
import com.senac.service.UsuarioServiceLocal;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 2928065641467162717L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		login(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		login(req, resp);
	}
	
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		UsuarioServiceLocal service = new UsuarioService();
		
		String login = req.getParameter("loginUser");
		String password = req.getParameter("passwordUser");
		
		Usuario user = service.login(login, password);
		
		if(user == null) {
			resp.sendRedirect("login.jsp?login=invalid");
		} else {
			req.getSession(true).setAttribute("sessionUser", user);
			resp.sendRedirect("index.jsp");
		}
	}
	
}
